package com.common.es.instance;

import com.common.es.config.EsConfig;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.common.es.config.EsConstant.DEFAULT_OPTIONS;

/**
 * @author 牧鱼
 * @Classname EsInstance
 * @Description TODO
 * @Date 2021/5/10
 */
@Component
public class EsInstance {

    private static final Logger log = LoggerFactory.getLogger(EsInstance.class);

    /**
     * restClient 客户端初始化
     */
    private RestHighLevelClient restClient = null;

    /**
     * 构造器注入实例化es连接对象
     * @param esConfig
     */
    public EsInstance(EsConfig esConfig) {
        log.info("初始化Es开始");
        long startTime = System.currentTimeMillis();
        // 创建Es编译对象
        RestClientBuilder builder = RestClient.builder( esConfig.initHttpHost() );
        //检测Es是否加需要认证
        if (esConfig.isAuth()){
            log.info("初始化Es授权：userName：<"+esConfig.getUserName()+"> password：<"+esConfig.getPassword()+">");
            // 创建 es 授权对象
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            //es账号密码（默认用户名为elastic）
            credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(esConfig.getUserName(), esConfig.getPassword()));
            builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    httpClientBuilder.disableAuthCaching();
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            });
            log.info("初始化Es授权成功");
        }
        restClient = new RestHighLevelClient(builder);
        log.info("初始化Es结束；耗时：{"+(System.currentTimeMillis()-startTime)+"}MS");
    }

    public RestHighLevelClient getRestClient() {
        return restClient;
    }
}
